<template>
  <div>

    <el-dialog title="菜单报表" :visible.sync="dialogShowMenuVisible">
    <div id="main" style="width: 1000px;height: 1000px"></div>
    </el-dialog>

    <el-button type="success" @click="DownLoad">导出Excel</el-button>
    <el-button type="warning" @click="showMenuForm">展开报表</el-button>
    <br><br><br>
    <el-form :inline="true" ref="queryForm" size="small" :model="formInline" v-show="showSearch" class="demo-form-inline">
      <el-form-item label="菜单名称">
        <el-input
            v-model="formInline.menuName"
            placeholder="请输入菜单名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="formInline.status" placeholder="菜单状态" clearable>
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getTableData">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            style="background-color: aquamarine"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            style="background-color: #42b983"
            @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getTableData"></right-toolbar>
    </el-row>

      <el-table
          v-if="refreshTable"
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%;margin-bottom: 20px;"
          row-key="id"
          :default-expand-all="isExpandAll"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
        <el-table-column
            prop="name"
            label="菜单名称"
            :show-overflow-tooltip="true"
            width="160">
        </el-table-column>
        <el-table-column
            prop="icon"
            label="图标"
            width="120"
            align="center">
          <template >
            <i class="el-icon-s-tools"></i>
          </template>
        </el-table-column>
        <el-table-column
            prop="parentId"
            label="父菜单ID"
            :show-overflow-tooltip="true"
            width="120">
        </el-table-column>
        <el-table-column
            prop="orderNum"
            label="显示顺序"
            width="100">
        </el-table-column>
        <el-table-column
            prop="path"
            label="路由地址"
            width="120">
        </el-table-column>
        <el-table-column
            prop="component"
            label="组件路径"
            width="120">
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            width="120">
          <template v-slot="s">
            <span v-if="s.row.status==1">停用</span>
            <span v-if="s.row.status==0">正常</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间"
            width="250">
        </el-table-column>
        <el-table-column
            prop="pic"
            label="图片"
            width="250">
          <template v-slot="s">
            <el-image
                style="width: 100px; height: 100px"
                :src="s.row.pic"></el-image>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="260">
          <template slot-scope="scope">
            <el-button style="background-color: antiquewhite" @click="handleClick(scope.row)" >查看</el-button>
            <el-button style="background-color: aqua" @click="updateMenu(scope.row)" >修改</el-button>
            <el-button style="background-color: beige" @click="deleteMenuById(scope.row)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>


    <el-dialog :title="title" :visible.sync="dialogTableVisible" width="680px" append-to-body>
      <el-form ref="formName" :model="formName" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单" :label-width="formLabelWidth" prop="parentId">
              <el-input v-model="selectedNodeName" @focus="showTree = true" placeholder="主目录" ></el-input>
              <el-popover
                  ref="treePopover"
                  v-model="showTree"
                  placement="bottom-start"
                  width="260"
                  trigger="click">
                <el-tree
                    v-if="refreshTable"
                    :data="treeData"
                    :props="treeProps"
                    :default-expand-all="isExpandAll"
                    node-key="id"
                    @node-click="handleTreeCurrentChange">
                </el-tree>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="formName.menuType">
                <el-radio label="M" >目录</el-radio>
                <el-radio label="C" >菜单</el-radio>
                <el-radio label="F" >按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="formName.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="formName.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formName.menuType != 'F'">
            <el-form-item prop="isFrame">
              <span slot="label">
                <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                是否外链
              </span>
              <el-radio-group v-model="formName.isFrame">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formName.menuType != 'F'">
            <el-form-item prop="path">
              <span slot="label">
                <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                路由地址
              </span>
              <el-input v-model="formName.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formName.menuType == 'C'">
            <el-form-item prop="component">
              <span slot="label">
                <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                组件路径
              </span>
              <el-input v-model="formName.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formName.menuType != 'M'">
            <el-form-item prop="perms">
              <el-input v-model="formName.perms" placeholder="请输入权限标识" maxlength="100" />
              <span slot="label">
                <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                权限字符
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formName.menuType == 'C'">
            <el-form-item prop="query">
              <el-input v-model="formName.query" placeholder="请输入路由参数" maxlength="255" />
              <span slot="label">
                <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                路由参数
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formName.menuType == 'C'">
            <el-form-item prop="isCache">
              <span slot="label">
                <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                是否缓存
              </span>
              <el-radio-group v-model="formName.isCache">
                <el-radio label="0" >缓存</el-radio>
                <el-radio label="1" >不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formName.menuType != 'F'">
            <el-form-item prop="visible">
              <span slot="label">
                <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                显示状态
              </span>
              <el-radio-group v-model="formName.visible">
                <el-radio  label="0" >显示</el-radio>
                <el-radio  label="1" >隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status">
              <span slot="label">
                <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                菜单状态
              </span>
              <el-radio-group v-model="formName.status">
                <el-radio label="0" >正常</el-radio>
                <el-radio label="1" >停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
          <el-form-item prop="pic">
              <span slot="label">
                图片
              </span>
            <el-upload
                class="avatar-uploader"
                action="http://192.168.137.1:8888/system/menu/upload/"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formName')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts';
export default {
  name: "MenuView",
  data() {
    return {
      loading: true,
      tableData:[],
      formInline:{},
      showSearch: true,
      dialogTableVisible: false,
      dialogShowMenuVisible: false,
      dialogTable:false,
      refreshTable: true,
      isExpandAll: false,
      formLabelWidth:'120px',
      selectedNodeName:'',
      treeData:[],
      title: "",
      formName:{},
      imageUrl:'',
      showTree:false,
      rules: {
        menuName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ],
        path: [
          { required: true, message: "路由地址不能为空", trigger: "blur" }
        ]
      },
      treeProps:{
        children: 'children',
        label: 'name',
        value: 'id',
      }
    }
  }, methods: {
      // 显示菜单报表
      showMenuForm(){
          this.dialogShowMenuVisible = true;
        this.$nextTick(() => {
          this.initEcharts();
        });
      },
      initEcharts() {
        let formData = []
        let xdata = []
        let ydata = []

        var chartDom = document.getElementById('main');
        var myChart = echarts.init(chartDom);

        this.axios.post("system/menu/showMenu").then(res => {
          formData = res.data;
          console.log(formData)

          xdata = formData.data.map(item => item.xdata);
          ydata = formData.data.map(item => item.ydata);

          const option = {
            xAxis: {
              type: 'category',
              data: xdata
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                data: ydata,
                type: 'bar'
              }
            ]
          };

          option && myChart.setOption(option);
        });
      },
      getTableData(){
        this.axios.post("/system/menu/list1",this.formInline).then(res=>{
          this.tableData=res.data.data;
          this.loading = false;
        })
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.selectedNodeName='';
        this.imageUrl='';
        this.reset();
        this.dialogTableVisible = true;
        this.title = "添加菜单";
        this.getTableData();
        if (row != null && row.menuId) {
          this.formName.parentId = row.menuId;
        } else {
          this.formName.parentId = 0;
        }
      },
      //修改按钮
      updateMenu(row){
        this.getTableData();
        this.axios.post("/system/menu/treeselect?menuId="+row.id).then(res=>{
          this.formName=res.data.data;
          this.imageUrl=row.pic;
          this.selectedNodeName=row.name;
          this.dialogTableVisible = true;
          this.title = "修改菜单";
        })
      },
      // 取消按钮
      cancel() {
        this.dialogTableVisible = false;
        this.reset();
      },
      DownLoad(){
        window.open("http://192.168.137.1:9017/menu/easyExcel");
      },
      handleQuery() {
        this.getTableData();
      },
      /** 展开/折叠操作 */
      toggleExpandAll() {
        this.refreshTable = false;
        this.isExpandAll = !this.isExpandAll;
        this.$nextTick(() => {
          this.refreshTable = true;
        });
      },
    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.formName.menuId!=undefined){
              this.axios.post("/system/menu/updateMenu",this.formName).then(res => {
                if (res.data.code==200){
                  this.$message.success("修改成功");
                  this.dialogTableVisible = false;
                  this.getTableData();
                }else {
                  this.$message.error("修改失败");
                }
              });
            }else {
              this.axios.post("/system/menu/addMenu",this.formName).then(res => {
                if (res.data.code==200){
                  this.$message.success("添加成功");
                  this.dialogTableVisible = false;
                  this.getTableData();
                }else {
                  this.$message.error("添加失败");
                }
              });
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      /** 删除按钮操作 */
      deleteMenuById(row) {
        alert(row.id)
        this.$confirm('是否确认删除名称为"' + row.name + '"的数据项？','提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.axios.post("/system/menu/deleteMenuById?menuId="+row.id).then(res => {
            if (res.data.code==200){
              this.$message.success(res.data.msg);
              this.getTableData();
            }else {
              this.$message.error(res.data.msg);
            }
          });
        }).catch(() => {
          this.$message.info("已取消删除");
        });
      },
      handleTreeCurrentChange(data){
        //用戶选择树节点时的回调
        this.formName.parentId=data.id;
        this.selectedNodeName=data.name;
        console.log(data);
        this.showTree = false;
      },
      loadTreeData(){
        this.axios.post("/system/menu/list1",this.formInline).then(res=>{
          this.treeData=res.data.data;
        })
      },
      reset() {
        this.formName = {
          menuName: '',
          parentId: '',
          orderNum: '',
          path: '',
          component: '',
          query: '',
          icon: '',
          isFrame: '1',
          menuType: 'M',
          visible: '0',
          status: '0',
          isCache: '0',
        };
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.formName.pic=res;
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
  }, created() {
      this.getTableData();
      this.loadTreeData();
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>